package Tiger;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;


import Translate.Translate;

import Parse.*;
import Absyn.*;

public class Parser {

	public ErrorMsg.ErrorMsg errorMsg;

	public Exp absyn;

	public Parser(String filename) {
		java_cup.runtime.Symbol symbol;
		String filename1=filename;
		filename = filename1;
		errorMsg = new ErrorMsg.ErrorMsg(filename);
		final Frame.Frame frame = new Mips.MipsFrame();
		{
			java.io.InputStream inp;
			try {
				inp = new java.io.FileInputStream(filename);
			} catch (java.io.FileNotFoundException e) {
				System.err.println("File not found: " + filename);
				return;
			}
			parser parser = new parser(new Parse.Yylex(inp, errorMsg), errorMsg);
			/* open input files, etc. here */
			
			//System.out.println("Parsing: " + filename);
			try {
				symbol = parser./*debug_*/parse();
				absyn = (Exp) (symbol.value);
			} catch (Exception e) {
				//e.printStackTrace();
				//throw new Error(e.toString());
				
			} finally {
				try {
					inp.close();
				} catch (java.io.IOException e) {
				}
			}
			
			if (errorMsg.anyErrors) return;
			
			
			//System.out.println("Type checking: " + filename);
			Translate translate = new Translate(frame);
		     Semant.Semant semant = new Semant.Semant(translate, errorMsg);
			//semant.Semant semant = new semant.Semant(errorMsg);
			semant.transProg(absyn);
			
			/*try {
				FileOutputStream Out=new FileOutputStream("IPKS_info.txt",true);
				OutputStreamWriter OutStrWriter=new OutputStreamWriter(Out);
		        BufferedWriter BWriter =new BufferedWriter(OutStrWriter); 
		        


			} catch (java.io.IOException e) {
				
			}*/
			if (errorMsg.anyErrors) return;
			else {
				System.out.println("parsed successfully, "+filename1+".abs"+" has been generated.");
			}
			PrintStream out;
/*			try{
				
				out = new PrintStream(
						new BufferedOutputStream(
								new FileOutputStream(filename1+".abs")));								
				System.setOut(out);
			
				Print printer = new Print(out);
				printer.prExp(absyn,0);				
				out.close();				
			}catch(java.io.IOException e){
				
			}
			
			Print printer = new Print(System.out);
			printer.prExp(absyn,0);*/
			
		}
	}


	public static  void main(String[] args) {
		if(args.length<1) {
			System.out.println("tcc: no input file");
			return;
		}
		String s,filename;
		s = args[0];
		if(!s.contains(".tig")) {
			System.out.println("tcc: need .tig file input");
			return;
		}
		filename=s.replaceAll(".tig", "");
		System.out.println(filename);
		Parser parser = new Parser(filename);
		System.out.println("\n==========");

	}
			
			
		

}
